include("${CMAKE_CURRENT_LIST_DIR}/RealmTargets.cmake")

# Find dependencies
include(CMakeFindDependencyMacro)

set(REALM_NEEDS_OPENSSL OFF)
if(UNIX AND NOT APPLE)
    set(REALM_NEEDS_OPENSSL ON)
elseif(TARGET Realm::Sync AND CMAKE_SYSTEM_NAME MATCHES "^Windows")
    set(REALM_NEEDS_OPENSSL ON)
    set(REALM_USE_SYSTEM_OPENSSL ON)
endif()
if(REALM_NEEDS_OPENSSL)
    if(REALM_USE_SYSTEM_OPENSSL)
        # Use system OpenSSL
        find_dependency(OpenSSL VERSION @OPENSSL_VERSION_MAJOR_MINOR@)
    else()
        # Use our OpenSSL
        if(NOT OpenSSL_DIR)
            if(NOT EXISTS ${CMAKE_BINARY_DIR}/openssl/lib/cmake/OpenSSL/OpenSSLConfig.cmake)
                if(ANDROID)
                    set(OPENSSL_URL "http://static.realm.io/downloads/openssl/@OPENSSL_VERSION@/Android/${CMAKE_ANDROID_ARCH_ABI}/openssl.tar.gz")
                else()
                    set(OPENSSL_URL "http://static.realm.io/downloads/openssl/@OPENSSL_VERSION@/Linux/x86_64/openssl.tar.gz")
                endif()

                message(STATUS "Getting ${OPENSSL_URL}...")
                file(DOWNLOAD "${OPENSSL_URL}" "${CMAKE_BINARY_DIR}/openssl/openssl.tar.gz" STATUS download_status)

                list(GET download_status 0 status_code)
                if (NOT "${status_code}" STREQUAL "0")
                    message(FATAL_ERROR "Downloading ${OPENSSL_URL}... Failed. Status: ${download_status}")
                endif()
                message(STATUS "Uncompressing OpenSSL...")
                execute_process(
                    COMMAND ${CMAKE_COMMAND} -E tar xfz "openssl.tar.gz"
                    WORKING_DIRECTORY "${CMAKE_BINARY_DIR}/openssl"
                )
            endif()

            set(OpenSSL_DIR "${CMAKE_BINARY_DIR}/openssl/lib/cmake/OpenSSL")
        endif()
        find_package(OpenSSL REQUIRED CONFIG)
        target_link_libraries(OpenSSL::SSL INTERFACE OpenSSL::Crypto)
    endif()
endif()

set(THREADS_PREFER_PTHREAD_FLAG ON)
find_dependency(Threads)

# Use Zlib for Sync, but allow integrators to override it
# Don't use find_library(ZLIB) on Apple platforms - it hardcodes the path per platform,
# so for an iOS build it'll use the path from the Device plaform, which is an error on Simulator.
# Just use -lz and let Xcode figure it out
if(TARGET Realm::Sync AND NOT APPLE AND NOT TARGET ZLIB::ZLIB)
    find_dependency(ZLIB)
endif()